package com.rp.system.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.rp.common.utils.JsonUtil;
import com.rp.common.utils.RpUtil;
import com.rp.common.vo.PageData;
import com.rp.controller.RpController;
import com.rp.system.po.HomePanel;
import com.rp.system.service.PanelService;


@Controller
@RequestMapping("/rp/system/panelMng/")
public class PanelController extends RpController {
	
	@Autowired
	private PanelService panelService;

	@RequestMapping("showHome")
	public ModelAndView showHome() {
		
		List<HomePanel> panels = panelService.getHpDao().find("from HomePanel where enabled2 = '1' order by panelSort asc");
		
		model.put("panels", panels);
		
		return forward("/rp/home.jsp");
	}
	
	@RequestMapping("showPanelGrid")
	public ModelAndView showPanelGrid() {
		
		return forward("/rp/system/panelMng/panelGrid.jsp");
	}
	
	@ResponseBody
	@RequestMapping("getPanelsByPage")
	public PageData getPanelsByPage() {

		Page<Record> jfinalPage = Db.use("rpDb").paginate(
				pageParam.getPageNumber(), pageParam.getPageSize(), "select *",
				"from RP_SYSTEM_PANELS rp " + pageParam.getOrderBy("rp"));
		
		return new PageData(jfinalPage.getTotalRow(),
				RpUtil.jfinalPageToList(jfinalPage));
	}
	
	@ResponseBody
	@RequestMapping("savePanels")
	public String savePanels(String data) {
		try {
			List<HomePanel> panels = JsonUtil.jsonToList(data, "com.rp.system.po.HomePanel");
			for (HomePanel panel : panels) {
				if(panel.getId() == null){
					panelService.addPanel(panel);
				}else{
					panelService.updatePanel(panel);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	@ResponseBody
	@RequestMapping("deletePanels")
	public String deletePanels(String data) {
		try {
			List<HomePanel> panels = JsonUtil.jsonToList(data, "com.rp.system.po.HomePanel");
			for (HomePanel panel : panels) {
				panelService.deletePanel(panel.getId());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
}
